package com.jms.fu.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.jms.fu.exception.DAOException;
import com.jms.fu.model.bean.App;
import com.jms.fu.model.bo.AppBO;

public class GetAppBySearch extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		try {
			PrintWriter out = response.getWriter();
			String search = request.getParameter("searchText");
			AppBO appbo = new AppBO();
			ArrayList<App> listApp =  new ArrayList<App>();
			listApp = appbo.getAppBySearch(search);
			String applistHTML = "";
			
			for (App temp : listApp) {
				ArrayList<String> avatar = appbo.getNumberOfFile(getServlet().getServletContext().getRealPath("/")+temp.getLink()+"/Avatar");
				String avatarLink;
				if(avatar.size()==0){
					avatarLink = "references/images/avatar.jpg"; 
				}else{
					avatarLink = temp.getLink()+"/Avatar/"+avatar.get(0);
				}
				applistHTML +="<li class='list-group-item'> "
						+ " <div class='col-xs-12 col-sm-3'> <img src='"+avatarLink+"'style='width: 50px;height: 50px;'> </div>"
						+ "<div class='col-xs-12 col-sm-9'> <span class='price'>"+(temp.getPrice() > 0 ? (temp.getPrice()+"$") : "Free")+"</span><br> "
						+ "<a class='item-g' href='getAppDetail.jms?appid="+temp.getAppId()+"'>"+temp.getAppName()+"</a> </div>"
						+ " <div class='clearfix'></div></li>";
			}
			out.print(applistHTML);
			out.close();
		} catch (IOException | DAOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
